import mongoose, { Document, Schema } from 'mongoose';

export interface IRole extends Document {
    name: string;   // 角色名称
    code: string;   // 角色代码
    description?: string; // 角色描述
    type: mongoose.Schema.Types.ObjectId;  // 角色类型
    sort: number;  // 角色排序
    tenantId: any;  // 所属租户ID
    isActive: boolean;      // 是否激活
    createdBy: mongoose.Schema.Types.ObjectId,   // 创建人ID
    updatedBy: mongoose.Schema.Types.ObjectId,   // 更新人ID
}

const roleSchema = new Schema<IRole>({
    name: {
        type: String,
        required: [true, '角色名称是必填项'],
        trim: true,
        minlength: [2, '角色名称至少需要2个字符'],
        maxlength: [50, '角色名称不能超过50个字符']
    },

    code: {
        type: String,
        required: [true, '角色代码是必填项'],
        trim: true,
        unique: true,
        minlength: [2, '角色代码至少需要2个字符'],
        maxlength: [50, '角色代码不能超过50个字符']
    },
    description: {
        type: String,
        trim: true,
        minlength: [2, '角色描述至少需要2个字符'],
        maxlength: [200, '角色描述不能超过200个字符']
    },
    type: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Dic',
        required: [true, '角色类型是必填项'],
        trim: true,
        minlength: [2, '角色类型至少需要2个字符'],
        maxlength: [50, '角色类型不能超过50个字符']
    },
    sort: {
        type: Number,
        required: [true, '角色排序是必填项'],
        default: 0
    },
    tenantId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Tenant',
        required: [true, '所属租户ID是必填项'],
    },
    isActive: {
        type: Boolean,
        default: true
    },
    createdBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
    },
    updatedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
    },
}, {
    timestamps: true // 自动添加 createdAt 和 updatedAt
});

// 创建索引
roleSchema.index({ name: 1, code: 1, tenantId: 1 });

// 虚拟字段（不存储在数据库中）
roleSchema.virtual('displayName').get(function () {
    return `${this.name} (${this.code}) [${this.tenantId}]`;
});

// 实例方法
roleSchema.methods.toJSON = function () {
    const role = this.toObject();
    return role;
};


export const RoleModel = mongoose.model<IRole>('Role', roleSchema);
